<template>
  <div class="app-container">
    <!-- 工具条 -->
    <div>
      <el-button
        type="danger"
        size="mini"
        @click="openBunner()"
        v-if="hasPerm('user.add')"
        >轮滑图片添加</el-button
      >
    </div>

    <!-- banner列表 -->
    <el-table
      :data="list"
      stripe
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="序号" width="70" align="center">
        <template slot-scope="scope">
          {{ (page - 1) * limit + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="title" label="标题" width="150" />
      <el-table-column
        prop="imageUrl"
        header-align="center"
        align="center"
        label="轮滑图片"
      >
        <template slot-scope="scope">
          <img :src="scope.row.imageUrl" style="width: 400px; height: 200px" />
        </template>
      </el-table-column>
      <el-table-column prop="linkUrl" label="链接" width="180" />
      <el-table-column prop="gmtCreate" label="创建时间" width="180" />

      <el-table-column label="操作" width="230" align="center">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click="openBunner(scope.row.id)"
          ></el-button>
          <el-button
            type="danger"
            size="mini"
            icon="el-icon-delete"
            @click="removeDataById(scope.row.id)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加组件 -->
    <el-dialog
      title="添加Bunner"
      :visible.sync="dialogVisible"
      width="40%"
      :before-close="closeBunner"
    >
      <el-form ref="bannerInfo" :model="bannerInfo" label-width="120px">
        <el-form-item label="标题">
          <el-input v-model="bannerInfo.title" />
        </el-form-item>
        <el-form-item label="轮滑图片">
          <el-upload
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :action="BASE_API + '/eduoss/fileoss'"
            class="avatar-uploader"
          >
            <img
              v-if="bannerInfo.imageUrl"
              :src="bannerInfo.imageUrl"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="链接">
          <el-input v-model="bannerInfo.linkUrl" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeBunner()">取 消</el-button>
        <el-button type="primary" @click="saveOrUpdate()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分页组件 -->
    <el-pagination
      :current-page="page"
      :total="total"
      :page-size="limit"
      :page-sizes="[5, 10, 20, 30, 40, 50, 100]"
      style="padding: 30px 0; text-align: center"
      layout="sizes, prev, pager, next, jumper, ->, total, slot"
      @current-change="fetchData"
      @size-change="changeSize"
    />
  </div>
</template>

<script>
import banner from "@/api/cms/banner";

const defaultForm = {
  title: "",
  imageUrl: "",
  linkUrl: "",
};

export default {
  data() {
    return {
      list: [], // 讲师列表
      bannerInfo: defaultForm,
      total: 0, // 数据库中的总记录数
      page: 1, // 默认页码
      limit: 10, // 每页记录数
      multipleSelection: [], // 批量选择中选择的记录列表
      dialogVisible: false, //添加弹框
      BASE_API: process.env.BASE_API, // 接口API地址
    };
  },

  created() {
    console.log("list created......");
    this.fetchData();
  },

  mounted() {
    console.log("list mounted......");
  },

  methods: {
    //上传封面成功调用的方法
    handleAvatarSuccess(res, file) {
      this.bannerInfo.imageUrl = res.data.url;
    },
    //上传之前调用的方法
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },

    // 当页码发生改变的时候
    changeSize(size) {
      console.log(size);
      this.limit = size;
      this.fetchData(1);
    },

    //打开弹框
    openBunner(id) {
      if (id) {
        banner.getById(id).then((response) => {
          this.bannerInfo = response.data;
          this.dialogVisible = true;
        });
      } else {
        this.dialogVisible = true;
      }
    },

    //关闭弹框
    closeBunner() {
      this.bannerInfo = defaultForm;
      this.dialogVisible = false;
    },

    saveOrUpdate() {
      if (!this.bannerInfo.id) {
        this.saveData();
      } else {
        this.updateData();
      }
    },

    // 新增讲师
    saveData() {
      banner.save(this.bannerInfo).then((response) => {
        if (response.success) {
          this.$message({
            type: "success",
            message: response.message,
          });
          this.$router.push({ path: "/cms/banner/list" });
          this.dialogVisible = false;
          this.bannerInfo = defaultForm;
          this.fetchData();
        }
      });
    },

    // 根据id更新记录
    updateData() {
      // teacher数据的获取
      banner.updateById(this.bannerInfo).then((response) => {
        if (response.success) {
          this.$message({
            type: "success",
            message: response.message,
          });
          this.$router.push({ path: "/cms/banner/list" });
          this.dialogVisible = false;
          this.bannerInfo = defaultForm;
          this.fetchData();
        }
      });
    },

    // 加载讲师列表数据
    fetchData(page = 1) {
      console.log("翻页。。。" + page);
      // 异步获取远程数据（ajax）
      this.page = page;

      banner.getPageList(this.page, this.limit).then((response) => {
        this.list = response.data.items;
        this.total = response.data.total;
      });
    },

    // 重置查询表单
    resetData() {
      console.log("重置查询表单");
      this.searchObj = {};
      this.fetchData();
    },

    // 根据id删除数据
    removeDataById(id) {
      // debugger
      this.$confirm("此操作将永久删除该记录, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // promise
          // 点击确定，远程调用ajax
          return banner.removeById(id);
        })
        .then((response) => {
          this.fetchData(this.page);
          if (response.success) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    // 当表格复选框选项发生变化的时候触发
    handleSelectionChange(selection) {
      console.log("handleSelectionChange......");
      console.log(selection);
      this.multipleSelection = selection;
    },

    // 执行搜索
    // queryString：文本框中输入的值
    // cb：一个函数
    querySearch(queryString, cb) {
      console.log(queryString);
      console.log(cb);

      // teacher.selectNameByKey(queryString).then(response => {
      //   // 调用 callback 返回建议列表的数据
      //   cb(response.data.items)
      // })
    },
  },
};
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>


